package com.metaera.app.ui.adapters;

import android.content.Context;
import android.content.Intent;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.metaera.app.LocalConfigStore;
import com.metaera.app.R;
import com.metaera.app.controller.presenter.FollowAuthorPresenter;
import com.metaera.app.controller.view.BasicNetworkRequestView;
import com.metaera.app.controller.view.FollowAuthorView;
import com.metaera.app.data.model.HotColumnResponse;
import com.metaera.app.data.network.ApiParam;
import com.metaera.app.ui.activities.LoginActivity;
import com.metaera.app.ui.activities.UserProfileActivity;
import com.metaera.app.utils.image.GlideApp;

import java.util.List;

import androidx.annotation.NonNull;

/**
 * 热门专栏
 */
public class HotColumnAdapter extends BaseQuickAdapter<HotColumnResponse, BaseViewHolder> {

    public HotColumnAdapter() {
        this(null);
    }

    public HotColumnAdapter(List<HotColumnResponse> data) {
        super(R.layout.item_hot_column, data);

        addChildClickViewIds(R.id.button_follow);

        setOnItemChildClickListener((adapter, v, position) -> {

            if (v.getId() == R.id.button_follow) {

                if (LocalConfigStore.getInstance().isLogin()) {
                    FollowAuthorPresenter presenter = new FollowAuthorPresenter();
                    presenter.setModelAndView(new BasicNetworkRequestView<>(new FollowAuthorView((TextView) v)));
                    presenter.follow(getItem(position).getUser().getId(), !v.isSelected());

                } else {
                    v.getContext().startActivity(new Intent(v.getContext(), LoginActivity.class));
                }

            }
        });

        setOnItemClickListener((adapter, view, position) -> {
            Context context = view.getContext();
            context.startActivity(UserProfileActivity.newIntent(context, getItem(position).getUid()));
        });
    }

    @Override
    protected void convert(@NonNull BaseViewHolder holder, HotColumnResponse item) {
        HotColumnResponse.User user = item.getUser();
        ImageView ivAvatar = holder.getView(R.id.iv_avatar);
        TextView buttonFollow = holder.getView(R.id.button_follow);

        buttonFollow.setSelected(item.getIs_follow() == ApiParam.FOLLOW_AUTHOR);
        buttonFollow.setText(buttonFollow.isSelected() ? R.string.followed : R.string.follow);

        holder.setText(R.id.tv_name, user.getNickname())
                .setText(R.id.tv_introduction, user.getDesc());

        GlideApp.with(ivAvatar)
                .load(user.getAvatar_img())
                .avatar()
                .into(ivAvatar);
    }

}
